package com.sidianzhong.sdz.controller.common;

import com.sidianzhong.sdz.model.commond.FileInfoVo;
import com.sidianzhong.sdz.utils.ResultModel;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Api(description = "其他")
@Controller
@Component
public class OtherController {

    private String imgPath = "/usr/local/tomcat/webapps/img/";

    private String imgUrl = "http://noahglobal.me/img/";

    @ApiOperation(value = "上传图片")
    @RequestMapping(value = "/sendImage",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody

    public Object sendImage(
            @ApiParam(value = "传输图片", required = true)
            @RequestParam(name = "file") MultipartFile file
    ) {

        System.out.println(imgPath + imgUrl);
        try {
            if (ImageIO.read(file.getInputStream()) == null) {
                return new ResponseEntity<>(ResultModel.error(null), HttpStatus.OK);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //查找数据库是否由此用户

        String fileName = imgPath + file.getOriginalFilename();

        //保存图片
        try {
            File dest = new File(fileName);
            if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest); //保存文件
        } catch (IllegalStateException | IOException e) {
            return e;
        }
        FileInfoVo fileInfoVo = new FileInfoVo();
        fileInfoVo.setCreateTime(System.currentTimeMillis());
        fileInfoVo.setFileType("*image");
        fileInfoVo.setFileUrl(imgUrl + file.getOriginalFilename());
        return new ResponseEntity<>(ResultModel.ok(fileInfoVo), HttpStatus.OK);
    }
}
